package top.dotgo.web.base.config.security;

import com.thetransactioncompany.cors.CORSFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * @author : lin
 * @date : 2019/9/27 13:50
 */
@Configuration
public class SecurityConfiguration implements WebMvcConfigurer {


    @Bean
    public FilterRegistrationBean<Filter> securityFilter() {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new SecurityFilter());
        registrationBean.addUrlPatterns("/*");
        //注意: 在 spring security filter之后
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<Filter> corsFilter() {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CORSFilter());
        registrationBean.addUrlPatterns("/*");
        //注意: 在 spring security filter之后
        registrationBean.setOrder(0);

        registrationBean.addInitParameter("cors.allowGenericHttpRequests", "true");
        registrationBean.addInitParameter("cors.allowOrigin", "*");
        registrationBean.addInitParameter("cors.allowSubdomains", "false");
        registrationBean.addInitParameter("cors.supportedMethods", "GET, HEAD, POST,PUT,DELETE,OPTIONS");
        registrationBean.addInitParameter("cors.supportedHeaders", "*");
        registrationBean.addInitParameter("cors.exposedHeaders", "X-Test-1, X-Test-2");
        registrationBean.addInitParameter("cors.supportsCredentials", "true");
        registrationBean.addInitParameter("cors.maxAge", "3600");

        return registrationBean;
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getSecurityInterceptor()).order(1)
                .excludePathPatterns("/error")
                .addPathPatterns("/**");
    }

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    /**
     * <p>设置密码校验器</p>
     * NoOpPasswordEncoder 直接文本比较  equals
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
